<script setup lang='ts'>
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { useAddBuyers, useGetPageGroupBuyers, useRemoveBuyer } from '@fl/api/man-api'
import { SearchForm, SearchTable, SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'

const { isPending: removePending, mutate: removeMutate } = useRemoveBuyer()

const { isPending: addPending, mutate: addMutate } = useAddBuyers()

const id = defineModel<any>('id')

const form = ref()

const groupName = defineModel<any>('groupName')

const visible = defineModel<boolean>('visible', { required: true })

const tableRef = ref()

const isChooseEnterprise = ref<boolean>(false)

const dialogTitle = computed(() => '关联企业')

const initialState = {
    buyerName: '',
}

const state = ref(cloneDeep(initialState))

const columns = [
    {
        label: '企业名称',
        prop: 'buyerName',
    },
]

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}

const tablePage = ref(cloneDeep(initialPage))

const tableData = ref<any[]>([])

const gridOptions = computed<VxeGridProps>(() => {
    if (unref(isChooseEnterprise)) {
        return {
            checkboxConfig: {
                range: false,
                reserve: true,
            },
            columns: [
                { type: 'checkbox', width: 50 },
                { field: 'enterpriseName', title: '企业名称' },
                { field: 'enterpriseType', title: '企业类型' },
            ],
            height: 350,
            minHeight: 350,
            rowConfig: {
                keyField: 'id',
            },
        }
    }
    return {
        checkboxConfig: {
            range: false,
            reserve: true,
        },
        columns: [
            { field: 'enterpriseName', title: '企业名称' },
            { field: 'enterpriseType', title: '企业类型' },
            { slots: { default: 'operate' }, title: '操作' },
        ],
        height: 350,
        minHeight: 350,
        rowConfig: {
            keyField: 'id',
        },
    }
})

const params = computed(() => {
    return {
        buyerName: unref(state).buyerName,
        groupId: unref(id),
        isChooseEnterprise: unref(isChooseEnterprise),
        pageNum: unref(tablePage).currentPage,
        pageSize: unref(tablePage).pageSize,
    }
})

const { data, isLoading } = useGetPageGroupBuyers(params)

const loading = computed(() => removePending.value || isLoading.value || addPending.value)

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

function search(val: any) {
    state.value = cloneDeep(val)
    tablePage.value.currentPage = 1
}
function resetForm() {
    state.value = cloneDeep(initialState)
    tablePage.value.currentPage = 1
}
function confirmChooseEnterprise() {
    const selectedReserve = tableRef.value?.tableInstance?.getCheckboxReserveRecords()
    const selected = tableRef.value?.tableInstance?.getCheckboxRecords()
    const connected = [...selectedReserve, ...selected]
    if (!connected.length) {
        ElMessage.warning('请至少选择一条数据')
        return
    }
    const params = {
        enterpriseIds: connected.map((item: any) => item.id),
        groupId: unref(id),
    }
    addMutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
            tableRef.value?.tableInstance?.clearCheckboxRow()
            tableRef.value?.tableInstance?.clearCheckboxReserve()
            form.value.formInstance.handleReset()
            isChooseEnterprise.value = false
        },
    })
}

function cancelChooseEnterprise() {
    form.value.formInstance.handleReset()
    isChooseEnterprise.value = false
}
function cancel() {
    visible.value = false
}

function resetDialog() {
    id.value = ''
    groupName.value = ''
    form.value.formInstance.handleReset()
}

function associated() {
    form.value.formInstance.handleReset()
    isChooseEnterprise.value = true
}

function cancelAssociated(row: any) {
    const params = {
        enterpriseId: row.id,
        groupId: unref(id),
    }
    removeMutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

watchEffect(() => {
    if (data.value) {
        tableData.value = cloneDeep(data.value?.records) || []
        tablePage.value.total = data.value.total ?? 0
    }
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialogTitle"
                width="1000"
                @cancel="cancel"
                @closed="resetDialog"
    >
        <div class="mb-20">
            集团名称: {{ groupName }}
        </div>

        <el-button v-if="!isChooseEnterprise"
                   class="mb-20"
                   type="primary"
                   @click="associated"
        >
            关联企业
        </el-button>

        <SearchForm v-bind="state"
                    ref="form"
                    :columns="columns"
                    submit-text="查询"
                    class="mb-20"
                    @submit="search"
                    @reset="resetForm"
        />

        <SearchTable v-bind="gridOptions"
                     ref="tableRef"
                     v-model:pager="tablePage"
                     :seq-config="{ startIndex: (tablePage.currentPage - 1) * tablePage.pageSize }"
                     :loading="loading"
                     :data="tableData"
                     @page-change="handlePageChange"
        >
            <template #operate="{ row }">
                <el-button type="primary"
                           text
                           @click="cancelAssociated(row)"
                >
                    取消关联
                </el-button>
            </template>
        </SearchTable>

        <template #footer>
            <div class="mx-auto">
                <template v-if="isChooseEnterprise">
                    <el-button @click="cancelChooseEnterprise">
                        取消
                    </el-button>

                    <SubmitBtn type="primary"
                               @click="confirmChooseEnterprise"
                    >
                        提交
                    </SubmitBtn>
                </template>

                <template v-else>
                    <el-button @click="cancel">
                        取消
                    </el-button>
                </template>
            </div>
        </template>
    </PlusDialog>
</template>
